﻿using System.Collections.Specialized;
using System.ComponentModel;
using Microsoft.Collections.Specialized;

namespace Microsoft.Collections.ObjectModel
{
    public partial class ObservableCollectionEx<T> : INotifyCollectionItemChanged
    {
        public event NotifyCollectionItemChangedEventHandler CollectionItemChanged;

        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs args)
        {
            if (args.NewItems != null)
                foreach (T item in args.NewItems)
                    AddNotifyPropertyChangedHandler(item);
            if (args.OldItems != null)
                foreach (T item in args.OldItems)
                    RemoveNotifyPropertyChangedHandler(item);
        
            base.OnCollectionChanged(args);
        }

        void AddNotifyPropertyChangedHandler(T item)
        {
            if (item is INotifyPropertyChanged)
                (item as INotifyPropertyChanged).PropertyChanged += OnCollectionItemPropertyChanged;
        }

        void RemoveNotifyPropertyChangedHandler(T item)
        {
            if (item is INotifyPropertyChanged)
                (item as INotifyPropertyChanged).PropertyChanged -= OnCollectionItemPropertyChanged;
        }
        
        protected virtual void OnCollectionItemPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (CollectionItemChanged != null)
                CollectionItemChanged(this, new NotifyCollectionItemChangedEventArgs(e.PropertyName, sender));
        }
    }
}